package com.yhp.filter;

import com.yhp.bean.Users;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyFilter2 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter2初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("Filter2---开始");
        //登录验证
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String uri = request.getRequestURI();//请求地址
        System.out.println("uri:"+uri);
        //获得session中的用户信息
        Users users =(Users) request.getSession().getAttribute("u1");

        if(users == null){
            //还未登录,提示用户登录
            //对一些资源放行/cherkuname
            String key = request.getParameter("key");
            if("/js/jquery-1.8.3.min.js".endsWith(uri)||"index.jsp".endsWith(uri)||"/checkuname".endsWith(uri)||"/add.jsp".endsWith(uri)||"login".equals(key)||"/favicon.ico".endsWith(uri)){
                filterChain.doFilter(servletRequest, servletResponse);
            }else{
                //response.sendRedirect("/index.jsp");
                request.getRequestDispatcher("/index.jsp").forward(request,response);
            }

        }else{
            filterChain.doFilter(servletRequest,servletResponse);//调取下一个过滤器或者进入Servlet
        }

        System.out.println("Filter2---结束");
    }

    @Override
    public void destroy() {
        System.out.println("Filter销毁");
    }
}
